package com.xiaowu.commons.utils;

import java.io.BufferedWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

public class ExportCSV<T> {

	
	public static void exportCSVByList(List<?> dataset,String[][] headers,HttpServletResponse response,String title,String pattern) throws IOException{
		response.setCharacterEncoding("utf-8");
		response.setContentType("applicatoin/octet-stream");
		response.setHeader("Content-disposition","attachment; filename="+new String((title).getBytes("gbk"),"iso8859-1")+".csv");
		
		if(pattern==null){
			pattern = "yyyy-MM-dd HH:mm:ss";
		}
		BufferedWriter buffer  = new BufferedWriter(response.getWriter());
		for (short i = 0; i < headers.length; i++) {
			buffer.append(headers[i][0]).append(",");
		}
		buffer.newLine();
		
		for (int i = 0; i < dataset.size(); i++) {
			for (int j = 0; j < headers.length; j++) {
				Object object = ReflectionUtils.getFieldValue(dataset.get(i),headers[j][1]);
				//时间格式化
				if (object instanceof Date){
					 Date date = (Date) object;  
                     SimpleDateFormat sdf = new SimpleDateFormat(pattern);  
                     object = sdf.format(date);  
				}else if(object == null){
        			object = "-";
        		}
				buffer.append(object.toString()).append(",");
			}
			buffer.newLine();
		}
		//刷新该流中的缓冲。将缓冲数据写到目的文件中去。
		buffer.flush();
		//关闭此流，再关闭前会先刷新他。
		buffer.close();
		
	}
	
	public static void exportCSVByObject(List<List<Object>> dataset,HttpServletResponse response,String title){
	  
		try {
			response.setCharacterEncoding("utf-8");
			response.setContentType("applicatoin/octet-stream");
			response.setHeader("Content-disposition","attachment; filename="+new String((title).getBytes("gbk"),"iso8859-1")+".csv");
			
			BufferedWriter buffer  = new BufferedWriter(response.getWriter());
			for (List<Object> list : dataset) {
				for (Object object : list) {
					buffer.append(object+",");
				}
				buffer.newLine();
			}
			//刷新该流中的缓冲。将缓冲数据写到目的文件中去。
			buffer.flush();
			//关闭此流，再关闭前会先刷新他。
			buffer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
